package cn.lbf.stuniversity.utils;

import cn.lbf.stuniversity.vo.PageVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
public class PageUtil {

    public static Pageable initPage(PageVO page) {

        int pageNumber = page.getPageNumber();
        int pageSize = page.getPageSize();
        String sort = page.getSort();
        String order = page.getOrder();

        // 设置默认值
        if (pageNumber < 1) {
            pageNumber = 1;
        }
        if (pageSize < 1) {
            pageSize = 10;
        }

        Sort sortObj = null;
        if (StringUtils.isNotBlank(sort)) {
            Sort.Direction direction;
            if (StringUtils.isBlank(order)) {
                direction = Sort.Direction.DESC;
            } else {
                direction = Sort.Direction.valueOf(order.toUpperCase());
            }
            sortObj = Sort.by(direction, sort);
        }

        // 创建 Pageable 实例
        Pageable pageable;
        if (sortObj != null) {
            pageable = PageRequest.of(pageNumber - 1, pageSize, sortObj);
        } else {
            pageable = PageRequest.of(pageNumber - 1, pageSize);
        }

        return pageable;
    }
}